"use client";

import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toast } from "sonner";
import { format } from "date-fns";

export interface Feedback {
  id: string;
  student_id: string;
  content: string;
  created_at: string;
  status: number; // 0 未处理，1 已处理
}

export default function AdminFeedbackList() {
  const [feedbacks, setFeedbacks] = useState<Feedback[]>([]);

  const fetchFeedbacks = async () => {
    const res = await fetch("/api/feedback/list");
    const data = await res.json();
    setFeedbacks(data);
  };

  const handleMarkAsProcessed = async (id: string) => {
    const res = await fetch(`/api/feedback/${id}/status`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: 1 }),
    });
    if (res.ok) {
      toast.success("已标记为已处理");
      fetchFeedbacks(); // 刷新列表
    } else {
      toast.error("更新失败");
    }
  };

  useEffect(() => {
    fetchFeedbacks();
  }, []);

  return (
    <div className="p-6">
      <Card className="mx-6 p-6 border-gray-200 shadow-md rounded-md">
        <h2 className="text-xl font-bold mb-4 text-center">用户反馈列表</h2>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>学生ID</TableHead>
              <TableHead>反馈内容</TableHead>
              <TableHead>反馈时间</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {feedbacks.map((fb) => (
              <TableRow key={fb.id}>
                <TableCell>{fb.student_id}</TableCell>
                <TableCell className="max-w-[300px] break-words">
                  {fb.content}
                </TableCell>
                <TableCell>
                  {format(new Date(fb.created_at), "yyyy-MM-dd HH:mm")}
                </TableCell>
                <TableCell>{fb.status === 1 ? "已处理" : "未处理"}</TableCell>
                <TableCell>
                  {fb.status === 0 ? (
                    <Button
                      onClick={() => handleMarkAsProcessed(fb.id)}
                      variant="outline"
                    >
                      标记为已处理
                    </Button>
                  ) : (
                    <span className="text-gray-400">——</span>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
